package com.agw.crm.workbench.web.controller;

import com.agw.crm.settings.domain.User;
import com.agw.crm.settings.service.UserService;
import com.agw.crm.settings.service.impl.UserServiceImpl;
import com.agw.crm.utils.DateTimeUtil;
import com.agw.crm.utils.PrintJson;
import com.agw.crm.utils.ServiceFactory;
import com.agw.crm.utils.UUIDUtil;
import com.agw.crm.workbench.domain.Activity;
import com.agw.crm.workbench.domain.Clue;
import com.agw.crm.workbench.domain.Tran;
import com.agw.crm.workbench.domain.TranHistory;
import com.agw.crm.workbench.service.ActivityService;
import com.agw.crm.workbench.service.ClueService;
import com.agw.crm.workbench.service.CustomerService;
import com.agw.crm.workbench.service.TranService;
import com.agw.crm.workbench.service.impl.ActivityServiceImpl;
import com.agw.crm.workbench.service.impl.ClueServiceIpml;
import com.agw.crm.workbench.service.impl.CustomerServiceImpl;
import com.agw.crm.workbench.service.impl.TranServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TranController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //进入到市场活动控制器
        System.out.println("进入到交易活动控制器");
        //获取请求路径，根据请求路径调方法
        String path = request.getServletPath();

        if ("/workbench/transaction/add.do".equals(path)){
            add(request,response);
        }else if ("/workbench/transaction/getCustomerName.do".equals(path)){
            getCustomerName(request,response);
        }else if ("/workbench/transaction/save.do".equals(path)){
            save(request,response);
        }else if ("/workbench/transaction/detail.do".equals(path)){
            detail(request,response);
        }else if ("/workbench/transaction/getTranHistoryByTranId.do".equals(path)){
            getTranHistoryByTranId(request,response);
        }else if ("/workbench/transaction/changeStage.do".equals(path)){
            changeStage(request,response);
        }else if ("/workbench/transaction/getCharts.do".equals(path)){
            getCharts(request,response);
        }
    }

    private void getCharts(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始查询交易阶段记录");

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        //返回值应该是
        //data
        //["total":总条数,"dataList":{{value:60,name:01-资质审查}},{{value:}}...]
        Map<String,Object> map = ts.getCharts();

        PrintJson.printJsonObj(response,map);

    }

    private void changeStage(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始处理阶段变更");

        String id = request.getParameter("id");
        String stage = request.getParameter("stage");
        String money = request.getParameter("money");
        String expectedDate = request.getParameter("expectedDate");
        String editBy = ((User)request.getSession().getAttribute("user")).getName();
        String editTIme = DateTimeUtil.getSysTime();

        Tran tran = new Tran();
        tran.setId(id);
        tran.setStage(stage);
        tran.setMoney(money);
        tran.setExpectedDate(expectedDate);
        tran.setEditBy(editBy);
        tran.setEditTime(editTIme);

        //获取可能性
        Map<String,String> pMap = (Map<String,String>)this.getServletContext().getAttribute("pMap");
        String possibility = pMap.get(stage);
        tran.setPossibility(possibility);

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        boolean flag = ts.changeStage(tran);

        Map<String,Object> map = new HashMap<>();
        map.put("success",flag);
        map.put("t",tran);

        PrintJson.printJsonObj(response,map);
    }

    private void getTranHistoryByTranId(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始查询交易历史");
        String tranId = request.getParameter("tranId");

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        List<TranHistory> thList = ts.getTranHistoryByTranId(tranId);

        //从服务器中查询阶段对应的可能性，然后将可能性封装到历史记录中
        Map<String,String> pMap = (Map<String,String>)this.getServletContext().getAttribute("pMap");

        //遍历thList集合
        for (TranHistory tranHistory:thList){
            String stage = tranHistory.getStage();
            String possibility = pMap.get(stage);

            //将可能性封装到交易历史中
            tranHistory.setPossibility(possibility);
        }
        PrintJson.printJsonObj(response,thList);
    }

    private void detail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("查询交易详细信息");
        String id = request.getParameter("id");

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());
        Tran tran = ts.detail(id);


        /*
        关于可能性，需要从阶段中取值
         */
        //获取阶段
        String stage = tran.getStage();
        //阶段和可能性对应的值再服务器缓存中
        Map<String ,String> pMap =(Map<String ,String>) this.getServletContext().getAttribute("pMap");
        String possibility = pMap.get(stage);

        //将可能性封装到Tran中，方便以后使用
        tran.setPossibility(possibility);
        //通过请求转发跳转到交易详细信息页
        request.setAttribute("tran",tran);
        request.getRequestDispatcher("/workbench/transaction/detail.jsp").forward(request,response);


    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("开始保存新的交易");
        String id = UUIDUtil.getUUID();
        String owner = request.getParameter("owner");
        String money = request.getParameter("money");
        String name = request.getParameter("name");
        String expectedDate = request.getParameter("expectedDate");
        String customerName= request.getParameter("customerName");
        String stage = request.getParameter("stage");
        String type = request.getParameter("type");
        String source = request.getParameter("source");
        String activityId = request.getParameter("activityId");
        String contactsId = request.getParameter("contactsId");
        String createBy = ((User)request.getSession().getAttribute("user")).getName();
        String createTime = DateTimeUtil.getSysTime();
        String description = request.getParameter("description");
        String contactSummary = request.getParameter("contactSummary");
        String nextContactTime = request.getParameter("nextContactTime");

        Tran tran = new Tran();
        tran.setId(id);
        tran.setOwner(owner);
        tran.setMoney(money);
        tran.setName(name);
        tran.setExpectedDate(expectedDate);
        tran.setStage(stage);
        tran.setType(type);
        tran.setSource(source);
        tran.setActivityId(activityId);
        tran.setContactsId(contactsId);
        tran.setCreateBy(createBy);
        tran.setCreateTime(createTime);
        tran.setDescription(description);
        tran.setContactSummary(contactSummary);
        tran.setNextContactTime(nextContactTime);

        TranService ts = (TranService) ServiceFactory.getService(new TranServiceImpl());

        boolean flag = ts.save(tran,customerName);

        if (flag){
            //如果添加成功，通过重定向到index.jsp页面
            response.sendRedirect(request.getContextPath() + "/workbench/transaction/index.jsp");
        }


    }

    private void getCustomerName(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始查询客户名称列表（只查名称）");

        String name = request.getParameter("name");

        CustomerService cs = (CustomerService) ServiceFactory.getService(new CustomerServiceImpl());
        List<String> slist = cs.getNameByName(name);

        PrintJson.printJsonObj(response,slist);

    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("开始查询交易所有者");

        UserService userService = (UserService) ServiceFactory.getService(new UserServiceImpl());

        List<User> uList = userService.getUserList();

        //通过请求转发打开save.jsp页面
        request.setAttribute("uList",uList);

        request.getRequestDispatcher("/workbench/transaction/save.jsp").forward(request,response);
    }


}
